<?php
/**
 * 代码原链接 https://mp.weixin.qq.com/s?__biz=MzIxODQyNTU1MA==&amp;mid=2247484113&amp;idx=1&amp;sn=3d51e8b43ccda01663e06182f717669a&amp;chksm=97ebf370a09c7a66ff5fb9cf5de5bacdc16009b785b8f5a8519713b2975a8097c42d77a52c82&amp;scene=27&key=&ascene=1&uin=&devicetype=iMac+MacBookPro15%2C2+OSX+OSX+12.2.1+build(21D62)&version=13080712&nettype=WIFI&lang=zh_CN&countrycode=CN&fontScale=100
 */
interface Observer
{
    public function update(Subject $subject): void;
}

class ConcreteObserver implements Observer
{
    private $observerState = '';
    function update(Subject $subject): void
    {
        $this->observerState = $subject->getState();
        echo '执行观察者操作！当前状态：' . $this->observerState;
    }
}

class Subject
{
    private $observers = [];
    private $stateNow = '';
    public function attach(Observer $observer): void
    {
        array_push($this->observers, $observer);
    }
    public function detach(Observer $observer): void
    {
        $position = 0;
        foreach ($this->observers as $ob) {
            if ($ob == $observer) {
                array_splice($this->observers, ($position), 1);
            }
            ++$position;
        }
    }
    public function notify(): void
    {
        foreach ($this->observers as $ob) {
            $ob->update($this);
        }
    }
}

class ConcreteSubject extends Subject{
    public function setState($state)
    {
        $this->stateNow = $state;
        $this->notify();
    }

    public function getState()
    {
        return $this->stateNow;
    }
}